package cn.jiyun.service.impl;

import cn.jiyun.dao.domain.Product;
import cn.jiyun.dao.mapper.ProductMapper;
import cn.jiyun.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;

@Service
public class ProductServiceImpl  implements ProductService {
    @Autowired
    private ProductMapper productMapper;


    @Override
    public PageInfo getproducts(Product product, Integer pageNum, Integer limit) {
        //设置分页条件
        PageHelper.startPage(pageNum,limit);
        //获取分页数据
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        //模糊查询
        if(StringUtils.isNotEmpty(product.getName())){
            criteria.andLike("name",product.getName());
        }
        //时间区间查询
        if(product.getStart() !=null){
            criteria.andGreaterThanOrEqualTo("time",product.getStart());
        }

        if(product.getEnd() !=null){
            criteria.andLessThanOrEqualTo("time",product.getEnd());
        }

        List<Product> products = productMapper.selectByExample(example);
        //封装并返回
        return new PageInfo(products);
    }

    @Override
    public void addproduct(Product product) {
        productMapper.insertSelective(product);
    }

    @Override
    public Product findByid(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateProduct(Product product) {
        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public void deleteProducts(Integer[] id) {
        Example example = new Example(Product.class);
        example.createCriteria().andIn("id", Arrays.asList(id));
        productMapper.deleteByExample(example);
    }

    @Override
    public List<Product> findbyname(String name) {
        Example example = new Example(Product.class);
        example.createCriteria().andEqualTo("name",name);
        return productMapper.selectByExample(example);
    }
}
